<template>
  <div class="medical-record">
    <el-row :gutter="20">
      <!-- 左侧病历编辑区 -->
      <el-col :span="16">
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>门诊病历</span>
              <div class="button-group">
                <el-button type="primary" @click="saveRecord" :loading="loading">保存病历</el-button>
                <el-button @click="previewRecord">预览打印</el-button>
                <el-button type="info" @click="saveAsTemplate">存为模板</el-button>
              </div>
            </div>
          </template>

          <el-form
            ref="recordForm"
            :model="formData"
            :rules="rules"
            label-width="100px"
            class="record-form"
          >
            <!-- 患者信息 -->
            <el-descriptions title="患者信息" :column="3" border>
              <el-descriptions-item label="姓名">{{ patientInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ patientInfo.gender === 'M' ? '男' : '女' }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ patientInfo.age }}</el-descriptions-item>
              <el-descriptions-item label="科室">{{ patientInfo.department }}</el-descriptions-item>
              <el-descriptions-item label="医生">{{ patientInfo.doctor }}</el-descriptions-item>
              <el-descriptions-item label="就诊时间">{{ formatDateTime(patientInfo.visitTime) }}</el-descriptions-item>
            </el-descriptions>

            <!-- 病历内容 -->
            <el-form-item label="主诉" prop="chiefComplaint">
              <el-input
                v-model="formData.chiefComplaint"
                type="textarea"
                :rows="2"
                placeholder="请输入主诉"
              />
            </el-form-item>

            <el-form-item label="现病史" prop="presentIllness">
              <el-input
                v-model="formData.presentIllness"
                type="textarea"
                :rows="4"
                placeholder="请输入现病史"
              />
            </el-form-item>

            <el-form-item label="既往史" prop="pastHistory">
              <el-input
                v-model="formData.pastHistory"
                type="textarea"
                :rows="2"
                placeholder="请输入既往史"
              />
            </el-form-item>

            <el-form-item label="过敏史" prop="allergyHistory">
              <el-input
                v-model="formData.allergyHistory"
                type="textarea"
                :rows="2"
                placeholder="请输入过敏史"
              />
            </el-form-item>

            <el-form-item label="体格检查" prop="physicalExam">
              <el-input
                v-model="formData.physicalExam"
                type="textarea"
                :rows="4"
                placeholder="请输入体格检查结果"
              />
            </el-form-item>

            <el-form-item label="辅助检查" prop="auxiliaryExam">
              <el-input
                v-model="formData.auxiliaryExam"
                type="textarea"
                :rows="3"
                placeholder="请输入辅助检查结果"
              />
            </el-form-item>

            <el-form-item label="诊断" prop="diagnosis">
              <el-input
                v-model="formData.diagnosis"
                type="textarea"
                :rows="2"
                placeholder="请输入诊断结果"
              />
            </el-form-item>

            <el-form-item label="处理意见" prop="treatmentPlan">
              <el-input
                v-model="formData.treatmentPlan"
                type="textarea"
                :rows="3"
                placeholder="请输入处理意见"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧历史病历和模板 -->
      <el-col :span="8">
        <!-- 历史病历 -->
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>历史病历</span>
              <el-button type="primary" @click="refreshHistory">刷新</el-button>
            </div>
          </template>

          <el-table
            :data="historyRecords"
            style="width: 100%"
            v-loading="loading"
            :height="tableHeight"
          >
            <el-table-column prop="visitDate" label="就诊日期" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.visitDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="diagnosis" label="诊断" min-width="150" />
            <el-table-column prop="doctorName" label="医生" width="100" />
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="viewHistory(scope.row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>

        <!-- 病历模板 -->
        <el-card class="template-card">
          <template #header>
            <div class="card-header">
              <span>病历模板</span>
              <el-button type="primary" @click="refreshTemplates">刷新</el-button>
            </div>
          </template>

          <el-table
            :data="templates"
            style="width: 100%"
            :height="200"
          >
            <el-table-column prop="name" label="模板名称" min-width="150" />
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="applyTemplate(scope.row)"
                >
                  应用
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="deleteTemplate(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 模板保存对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="保存为模板"
      width="40%"
    >
      <el-form :model="templateForm" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="templateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 类型定义
interface MedicalRecord {
  id: number
  visitDate: string
  chiefComplaint: string
  presentIllness: string
  pastHistory: string
  allergyHistory: string
  physicalExam: string
  auxiliaryExam: string
  diagnosis: string
  treatmentPlan: string
  doctorName: string
}

interface Template {
  id: number
  name: string
  description: string
  content: {
    chiefComplaint: string
    presentIllness: string
    pastHistory: string
    allergyHistory: string
    physicalExam: string
    auxiliaryExam: string
    diagnosis: string
    treatmentPlan: string
  }
}

// 模拟患者信息
const patientInfo = ref({
  id: 1,
  name: '张三',
  gender: 'M',
  age: 35,
  department: '内科',
  doctor: '李医生',
  visitTime: '2024-04-29T10:00:00Z'
})

// 表单数据
const formData = ref({
  chiefComplaint: '',
  presentIllness: '',
  pastHistory: '',
  allergyHistory: '',
  physicalExam: '',
  auxiliaryExam: '',
  diagnosis: '',
  treatmentPlan: ''
})

// 表单验证规则
const rules = ref<FormRules>({
  chiefComplaint: [
    { required: true, message: '请输入主诉', trigger: 'blur' }
  ],
  diagnosis: [
    { required: true, message: '请输入诊断', trigger: 'blur' }
  ]
})

// 历史病历数据
const historyRecords = ref<MedicalRecord[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableHeight = ref('300px')

// 模板数据
const templates = ref<Template[]>([])
const templateDialogVisible = ref(false)
const templateForm = ref({
  name: '',
  description: ''
})

// 表单引用
const recordForm = ref<FormInstance>()

// 方法定义
const formatDateTime = (dateStr: string | undefined): string => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDate = (dateStr: string | undefined): string => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 保存病历
const saveRecord = async () => {
  if (!recordForm.value) return
  
  await recordForm.value.validate((valid) => {
    if (valid) {
      loading.value = true
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('病历保存成功')
        loading.value = false
        refreshHistory()
      }, 1000)
    }
  })
}

// 预览病历
const previewRecord = () => {
  window.print()
}

// 存为模板
const saveAsTemplate = () => {
  templateForm.value = {
    name: '',
    description: ''
  }
  templateDialogVisible.value = true
}

// 确认保存模板
const confirmSaveTemplate = () => {
  if (!templateForm.value.name) {
    ElMessage.warning('请输入模板名称')
    return
  }

  // 模拟API调用
  setTimeout(() => {
    ElMessage.success('模板保存成功')
    templateDialogVisible.value = false
    refreshTemplates()
  }, 500)
}

// 刷新历史病历
const refreshHistory = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    historyRecords.value = [
      {
        id: 1,
        visitDate: '2024-04-29',
        chiefComplaint: '发热3天',
        presentIllness: '患者3天前无明显诱因出现发热...',
        pastHistory: '无特殊',
        allergyHistory: '无',
        physicalExam: 'T: 38.5℃...',
        auxiliaryExam: '血常规：WBC 12.5...',
        diagnosis: '上呼吸道感染',
        treatmentPlan: '1. 口服布洛芬...',
        doctorName: '李医生'
      }
    ]
    total.value = 1
    loading.value = false
  }, 500)
}

// 查看历史病历
const viewHistory = (record: MedicalRecord) => {
  formData.value = {
    chiefComplaint: record.chiefComplaint,
    presentIllness: record.presentIllness,
    pastHistory: record.pastHistory,
    allergyHistory: record.allergyHistory,
    physicalExam: record.physicalExam,
    auxiliaryExam: record.auxiliaryExam,
    diagnosis: record.diagnosis,
    treatmentPlan: record.treatmentPlan
  }
}

// 刷新模板列表
const refreshTemplates = () => {
  // 模拟API调用
  setTimeout(() => {
    templates.value = [
      {
        id: 1,
        name: '感冒模板',
        description: '普通感冒诊断模板',
        content: {
          chiefComplaint: '发热、咳嗽',
          presentIllness: '患者近期受凉后出现...',
          pastHistory: '无特殊',
          allergyHistory: '无',
          physicalExam: 'T: 37.8℃...',
          auxiliaryExam: '',
          diagnosis: '普通感冒',
          treatmentPlan: '1. 多休息，多饮水...'
        }
      }
    ]
  }, 500)
}

// 应用模板
const applyTemplate = (template: Template) => {
  ElMessageBox.confirm(
    '应用模板将覆盖当前内容，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    formData.value = { ...template.content }
    ElMessage.success('模板应用成功')
  })
}

// 删除模板
const deleteTemplate = (template: Template) => {
  ElMessageBox.confirm(
    '确定要删除该模板吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('模板删除成功')
      refreshTemplates()
    }, 500)
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  refreshHistory()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  refreshHistory()
}

// 生命周期钩子
onMounted(() => {
  refreshHistory()
  refreshTemplates()
})
</script>

<style scoped>
.medical-record {
  padding: 20px;
}

.form-card,
.history-card,
.template-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.record-form {
  margin-top: 20px;
}

/* 添加表格和表单项之间的边距 */
.el-descriptions {
  margin-bottom: 20px;
}

.el-form-item {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 打印样式 */
@media print {
  .el-button,
  .pagination,
  .history-card,
  .template-card {
    display: none;
  }

  .el-col-16 {
    width: 100%;
  }
}
</style> 